window.addEventListener('load', function () {
    var avatarBtn = document.querySelector('.avatarBtn');
    var hiddenFun = document.querySelector('.hiddenFun');
    var token = sessionStorage.getItem('token');
    // 刷新token
    axios.post('http://47.113.197.172:80/user/login', {
        name: sessionStorage.getItem('name'),
        password: sessionStorage.getItem('password')
    })
        .then(Response => {
            // 获取登录的用户身份和token令牌
            var newToken = Response.data.token;
            sessionStorage.setItem('token', newToken);
        })
        .catch(err => {
            console.log(err);
        })


    var hiddenFunFlag = 0;
    avatarBtn.onclick = function () {
        if (hiddenFunFlag == 0) {
            hiddenFun.style.display = 'block';
            hiddenFunFlag = 1;
        } else {
            hiddenFun.style.display = 'none';
            hiddenFunFlag = 0;
        }
    }

    // 点击发布弹出选项框
    var publish = document.getElementById('publish');
    var publishContainer = document.querySelector('.publishContainer');
    var publicFlag = 0;
    publish.onclick = function () {
        if (publicFlag == 0) {
            publishContainer.style.display = 'block';
            publicFlag = 1;
        } else {
            publishContainer.style.display = 'none';
            publicFlag = 0;
        }
    }

    // 点击取消关闭选项框
    var cancel = document.querySelector('.cancel');
    cancel.onclick = function () {
        if (publicFlag == 0) {
            publishContainer.style.display = 'block';
            publicFlag = 1;
        } else {
            publishContainer.style.display = 'none';
            publicFlag = 0;
        }
    }

    // 点击我的主页跳转页面
    var goUserMes = this.document.querySelector('.goUserMes');
    goUserMes.onclick = function () {
        window.location.href = '../html/userMes.html';
    }
    // 新写一篇文章
    var goWrite = this.document.querySelector('.goWrite');
    goWrite.onclick = function () {
        window.location.href = '../html/articles.html';
    }

    // 获取全部的分类
    var listContainer = document.querySelector('.listContainer');
    var listContainerLis = listContainer.querySelectorAll('li');
    var category = null;
    for (var i = 0; i < listContainerLis.length; i++) {
        // 给每个按键添加索引号，便于之后获取该元素
        listContainerLis[i].setAttribute('index', i);
        // 点击事件
        listContainerLis[i].onclick = function () {
            // 获取索引号
            var index = this.getAttribute('index');
            // console.log(index);
            // 排他算法
            for (var i = 0; i < listContainerLis.length; i++) {
                listContainerLis[i].style.backgroundColor = '#f4f5f5';
                listContainerLis[i].style.color = '#86909c';
            }
            listContainerLis[index].style.backgroundColor = '#e8f3ff';
            listContainerLis[index].style.color = '#1d7dfa';

            // 获取选择的分类
            category = listContainerLis[index].innerHTML;
        }
    }

    // 增加摘要输入框的样式
    var addBrief = document.getElementById('addBrief');
    addBrief.onfocus = function () {
        this.style.backgroundColor = 'white';
        this.style.border = '1px solid rgb(51, 112, 255)';
        this.style.boxShadow = '4px 4px 4px rgb(215, 227, 255)';
    }
    addBrief.onblur = function () {
        this.style.backgroundColor = 'rgb(250, 250, 250';
        this.style.border = '1px solid rgb(230, 232, 235)';
        this.style.boxShadow = 'none';
    }


    // 文章内容
    var title = document.getElementById('title');
    var content = document.getElementById('content');
    var brief = document.getElementById('addBrief');

    // 获取选取封面的input
    var coverUrl = document.getElementById('coverUrl');
    var show = document.getElementById('show');
    var coverUrlValue = null;
    // 预览图片
    coverUrl.onchange = function () {
        // 获取图片的相关信息
        // 方法一：URL.createObjectURL()
        var data = this.files[0];
        // var newSrc = URL.createObjectURL(data);
        // show.src = newSrc;
        // console.log(show.src);

        // // 方法二：FileReader()
        var reader = new FileReader();
        // 当图片加载完时，把base64编码赋值给预览图片
        reader.addEventListener('load', function () {
            // console.log(reader.result);
            show.src = reader.result;
        });
        // 转换成base64格式才能显示
        reader.readAsDataURL(data);


        // 获取新的封面URL
        var coverFd = new FormData();
        coverFd.append('picture', coverUrl.files[0]);
        axios({
            method: 'post',
            url: 'http://47.113.197.172:80/upload/picture',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token
            },
            data: coverFd
        })
            .then(Response => {
                // console.log(Response.data.data.url);
                coverUrlValue = Response.data.data.url;
            })
            .catch(err => {
                // alert('提交失败');
            })
    }


    getFormArticles();
    // 获取文章已有的内容
    var title = document.getElementById('title');
    var content = document.getElementById('content');
    var brief = document.getElementById('addBrief');
    var show = document.getElementById('show');


    function getFormArticles() {
        var finalUrl = sessionStorage.getItem('finalUrl');
        axios({
            method: 'get',
            url: finalUrl,
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token
            },
        })
            .then(Response => {
                // console.log(Response.data.data);
                insertArticles(Response.data.data);
                updatePassage(Response.data.data);
            })

            .catch(err => {
                console.log('获取失败/token过期');
            })
    }




    // 填充已经有的值
    function insertArticles(data) {
        // 将获取到的文章信息填入现在的页面
        title.value = data.title;
        content.value = data.content;
        brief.value = data.brief;
        show.src = data.coverUrl;
        for (var i = 0; i < listContainerLis.length; i++) {
            if (listContainerLis[i].innerHTML == data.category) {
                listContainerLis[i].style.backgroundColor = '#e8f3ff';
                listContainerLis[i].style.color = '#1d7dfa';
                category = listContainerLis[i].innerHTML;
            }
        }
    }

    // 点击确认更新文章内容
    var sure = document.querySelector('.sure');
    function updatePassage(data) {
        sure.onclick = function () {
            var finalUrl = sessionStorage.getItem('finalUrl');
            // 判断是否文章各个值是否修改
            var newData = {};
            // 现在的值不等于原来的值
            if (title.value !== data.title) {
                // 将现在的值添加到发送对象中
                newData.title = title.value;
            }
            if (content.value !== data.content) {
                newData.content = content.value;
            }
            if (brief.value !== data.brief) {
                newData.brief = brief.value;
            }
            if (coverUrlValue !== data.coverUrl) {
                newData.coverUrl = coverUrlValue;
            }
            if (category !== data.category) {
                newData.category = category;
            }

            axios({
                method: 'patch',
                url: finalUrl,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': token
                },
                // 只更新改动了的数据
                data: newData,

            })
                .then(Response => {
                    alert('更新成功');
                    // 清除finalUrl
                    sessionStorage.removeItem('finalUrl');
                    // 文章更新成功后返回个人主页
                    window.location.href = '../html/userMes.html';
                })
                .catch(err => {
                    alert('更新失败');
                })
        }
    }


    // 登录成功后动态获取用户头像
    var avatarBtn = document.querySelector('.avatarBtn');
    addAvatar = function () {
        var id = sessionStorage.getItem('id');
        var baseUrl = 'http://47.113.197.172:80/user/info/';
        var finalUrl = baseUrl + id;
        axios.get(finalUrl)
            .then(Response => {
                avatarBtn.src = Response.data.data.avatar;
            })
            .catch(err => {
                console.log(err);
            })
    }
    addAvatar();





















})